package com.kedacom.freedomLabel.view.activity.report;

import android.app.AlertDialog;
import android.app.PendingIntent;
import android.app.ProgressDialog;
import android.arch.lifecycle.Observer;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.databinding.ViewDataBinding;
import android.hardware.usb.UsbDevice;
import android.hardware.usb.UsbManager;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.github.mjdev.libaums.UsbMassStorageDevice;
import com.github.mjdev.libaums.fs.FileSystem;
import com.github.mjdev.libaums.fs.UsbFile;
import com.github.mjdev.libaums.partition.Partition;
import com.kedacom.freedomLabel.AppExecutors;
import com.kedacom.freedomLabel.Options;
import com.kedacom.freedomLabel.R;
import com.kedacom.freedomLabel.base.BaseActivity;
import com.kedacom.freedomLabel.databinding.ActivityReportBinding;
import com.kedacom.freedomLabel.excel.AdditionalColumn;
import com.kedacom.freedomLabel.model.annotation.ItemCategory;
import com.kedacom.freedomLabel.model.bean.Business;
import com.kedacom.freedomLabel.model.bean.Category;
import com.kedacom.freedomLabel.model.bean.Item;
import com.kedacom.freedomLabel.model.excel.BusinessSheet;
import com.kedacom.freedomLabel.model.excel.BusinessTable;
import com.kedacom.freedomLabel.utils.ExcelUtils;
import com.kedacom.freedomLabel.utils.UsbHelper;
import com.kedacom.freedomLabel.viewmodel.ReportViewModel;
import com.kedacom.lego.adapter.recyclerview.LegoBaseRecyclerViewAdapter;
import com.kedacom.lego.annotation.ContentView;
import com.kedacom.lego.annotation.OnMessage;
import com.kedacom.lego.annotation.ViewModel;
import com.kedacom.lego.message.LegoMessageManager;
import com.seray.scaleviewlib.utils.ToastUtils;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Locale;


@ContentView(R.layout.activity_report)
@ViewModel(ReportViewModel.class)
public class ReportActivity extends BaseActivity<ActivityReportBinding, ReportViewModel> {
    private LegoBaseRecyclerViewAdapter reportAdapter;
    private int curPage = 1;
    private int totalPage = 1;
    private UsbManager mUsbManager;
    private UsbMassStorageDevice[] storageDevices;
    private static final String ACTION_USB_PERMISSION = "com.infol.density.USB_PERMISSION";
    IntentFilter filter = new IntentFilter(ACTION_USB_PERMISSION);
    PendingIntent pendingIntent;
    private ProgressDialog exportPd;
    private String excelName;
    private SimpleDateFormat sdfString = new SimpleDateFormat("yyyyMMdd", Locale.getDefault());
    private int everyPageSize = 6;




    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mUsbManager = (UsbManager) getSystemService(Context.USB_SERVICE);
        registerReceiver(usbReceiver, filter);
        pendingIntent = PendingIntent.getBroadcast(this, 0, new Intent(ACTION_USB_PERMISSION), 0);



       mViewModel.category.observe(this, new Observer<Category>() {
           @Override
           public void onChanged(@Nullable Category category) {
               mBinding.byItem.setText(category.name);
               mBinding.llItem.removeAllViews();
               for (int i = 0; i < category.columnNames.length; i++) {
                   addItemView(category.columnNames[i]);
               }
               mViewModel.getBusinessDataByItem(mViewModel.category.getValue().name);
           }
       });


        mViewModel.mItems.observe(this, new Observer<List<Item>>() {
            @Override
            public void onChanged(@Nullable List<Item> items) {
                //显示一个弹框
                showSingleDialog(items);
            }
        });

        mBinding.showRecy.setLayoutManager(new LinearLayoutManager(this));
        reportAdapter = new LegoBaseRecyclerViewAdapter(R.layout.item_report_business, new ArrayList(), com.kedacom.freedomLabel.BR.business) {
            @Override
            protected void onCustomBindItem(ViewDataBinding binding, int position) {
                super.onCustomBindItem(binding, position);
            }
        };
        reportAdapter.setEmptyView(this, R.layout.report_empty);
        mBinding.showRecy.setAdapter(reportAdapter);
        mViewModel.mBusinessLiveData.observe(this, new Observer<List<Business>>() {
            @Override
            public void onChanged(@Nullable List<Business> businesses) {
                reportAdapter.setData(businesses);
                //显示页码总数和数据
                setPageNum(businesses);
            }
        });
       mBinding.pageControlNext.setOnClickListener(new View.OnClickListener() {
           @Override
           public void onClick(View view) {
               beep();
               if (curPage == totalPage){
                   mBinding.pageControlNext.setOnClickListener(null);
                   mBinding.pageControlLast.setOnClickListener(this);
               }else {
                   curPage  = curPage+1;
                   mBinding.showRecy.scrollToPosition((curPage-1)*everyPageSize);
                   mBinding.pageControlNumber.setText(curPage+"/"+totalPage);
               }
           }
       });
       mBinding.pageControlLast.setOnClickListener(new View.OnClickListener() {
           @Override
           public void onClick(View view) {
               beep();
               if (curPage == 1){
                   mBinding.pageControlLast.setOnClickListener(null);
                   mBinding.pageControlNext.setOnClickListener(this);
               }else {
                   curPage = curPage-1;
                   mBinding.showRecy.scrollToPosition((curPage-1)*everyPageSize);
                   mBinding.pageControlNumber.setText(curPage+"/"+totalPage);
               }
           }
       });


       mViewModel.mCategorys.observe(this, new Observer<List<Category>>() {
           @Override
           public void onChanged(@Nullable List<Category> categories) {
               showCategory(categories);
           }
       });
       mBinding.byItem.setOnClickListener(new View.OnClickListener() {
           @Override
           public void onClick(View v) {
               beep();
              mViewModel.getAllCategory();
           }
       });
    }

    private void setPageNum(List<Business> businesses) {
        if (businesses != null && businesses.size() > 0) {
            curPage = 1;
            totalPage = (((businesses.size() % everyPageSize) == 0) ? 0 : 1) + businesses.size() / everyPageSize;
            mBinding.pageControlNumber.setText(curPage + "/" + totalPage);
        }
    }


    public void addItemView(String names) {
        View itemChildView = LayoutInflater.from(this).inflate(R.layout.item_busiitem, null);
        ((TextView) itemChildView.findViewById(R.id.itemName)).setText(names);
        itemChildView.setTag(mBinding.llItem.getChildCount());
        itemChildView.findViewById(R.id.itemValue).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                beep();
//                Intent intent = new Intent(view.getContext(), ItemSelectActivity.class);
                String type = ItemCategory.ITEM_1;
                switch ((int) (itemChildView.getTag())) {
                    case 0:
                        type = ItemCategory.ITEM_1;
//                        intent.putExtra(Options.KEY_ITEM_CATEGORY, ItemCategory.ITEM_1);
//                        intent.putExtra(Options.SELECT_ITEM_FROM, "report");
//                        startActivity(intent);
                        break;
                    case 1:
                        type = ItemCategory.ITEM_2;
//                        intent.putExtra(Options.KEY_ITEM_CATEGORY, ItemCategory.ITEM_2);
//                        intent.putExtra(Options.SELECT_ITEM_FROM, "report");
//                        startActivity(intent);
                        break;
                    case 2:
                        type = ItemCategory.ITEM_3;
//                        intent.putExtra(Options.KEY_ITEM_CATEGORY, ItemCategory.ITEM_3);
//                        intent.putExtra(Options.SELECT_ITEM_FROM, "report");
//                        startActivity(intent);
                        break;
                    case 3:
                        type = ItemCategory.ITEM_4;
//                        intent.putExtra(Options.KEY_ITEM_CATEGORY, ItemCategory.ITEM_4);
//                        intent.putExtra(Options.SELECT_ITEM_FROM, "report");
//                        startActivity(intent);
                        break;
                    case 4:
                        type = ItemCategory.ITEM_5;
//                        intent.putExtra(Options.KEY_ITEM_CATEGORY, ItemCategory.ITEM_5);
//                        intent.putExtra(Options.SELECT_ITEM_FROM, "report");
//                        startActivity(intent);
                        break;
                    case 5:
                        type = ItemCategory.ITEM_6;
//                        intent.putExtra(Options.KEY_ITEM_CATEGORY, ItemCategory.ITEM_6);
//                        intent.putExtra(Options.SELECT_ITEM_FROM, "report");
//                        startActivity(intent);
                        break;
                    default:
                        break;
                }

                mViewModel.getCurCategoryItems(mViewModel.category.getValue().uuid,type);
            }
        });
        mBinding.llItem.addView(itemChildView);
    }


    @OnMessage(value = Options.MSG_REPORT_NO_CATEGORY)
    public void showNoCategory() {
        ToastUtils.showShort("请选择类别！");
    }


    @OnMessage(value = Options.MSG_REPORT_SELECT_ITEM)
    public void getReportSelectItem(Item item) {
        switch (item.category) {
            case ItemCategory.ITEM_1:
                mViewModel.ID1_Item.setValue(item);
                ((TextView) mBinding.llItem.getChildAt(0).findViewById(R.id.itemValue)).setText(item.value);
                ImageView imgDelete = mBinding.llItem.getChildAt(0).findViewById(R.id.imgdelete);
                imgDelete.setVisibility(View.VISIBLE);
                imgDelete.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        mViewModel.ID1_Item.setValue(null);
                        ((TextView) mBinding.llItem.getChildAt(0).findViewById(R.id.itemValue)).setText("");
                        imgDelete.setVisibility(View.GONE);
                        mViewModel.getBusinessDataByItem(mViewModel.category.getValue().name);
                    }
                });
                break;
            case ItemCategory.ITEM_2:
                mViewModel.ID2_Item.setValue(item);
                ((TextView) mBinding.llItem.getChildAt(1).findViewById(R.id.itemValue)).setText(item.value);
                ImageView imgDelete2 = mBinding.llItem.getChildAt(1).findViewById(R.id.imgdelete);
                imgDelete2.setVisibility(View.VISIBLE);
                imgDelete2.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        mViewModel.ID2_Item.setValue(null);
                        ((TextView) mBinding.llItem.getChildAt(1).findViewById(R.id.itemValue)).setText("");
                        imgDelete2.setVisibility(View.GONE);
                        mViewModel.getBusinessDataByItem(mViewModel.category.getValue().name);
                    }
                });
                break;
            case ItemCategory.ITEM_3:
                mViewModel.ID3_Item.setValue(item);
                ((TextView) mBinding.llItem.getChildAt(2).findViewById(R.id.itemValue)).setText(item.value);
                ImageView imgDelete3 = mBinding.llItem.getChildAt(2).findViewById(R.id.imgdelete);
                imgDelete3.setVisibility(View.VISIBLE);
                imgDelete3.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        mViewModel.ID3_Item.setValue(null);
                        ((TextView) mBinding.llItem.getChildAt(2).findViewById(R.id.itemValue)).setText("");
                        imgDelete3.setVisibility(View.GONE);
                        mViewModel.getBusinessDataByItem(mViewModel.category.getValue().name);
                    }
                });
                break;
            case ItemCategory.ITEM_4:
                mViewModel.ID4_Item.setValue(item);
                ((TextView) mBinding.llItem.getChildAt(3).findViewById(R.id.itemValue)).setText(item.value);
                ImageView imgDelete4 = mBinding.llItem.getChildAt(3).findViewById(R.id.imgdelete);
                imgDelete4.setVisibility(View.VISIBLE);
                imgDelete4.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        mViewModel.ID4_Item.setValue(null);
                        ((TextView) mBinding.llItem.getChildAt(3).findViewById(R.id.itemValue)).setText("");
                        imgDelete4.setVisibility(View.GONE);
                        mViewModel.getBusinessDataByItem(mViewModel.category.getValue().name);
                    }
                });
                break;
            case ItemCategory.ITEM_5:
                mViewModel.ID5_Item.setValue(item);
                ((TextView) mBinding.llItem.getChildAt(4).findViewById(R.id.itemValue)).setText(item.value);
                ImageView imgDelete5 = mBinding.llItem.getChildAt(4).findViewById(R.id.imgdelete);
                imgDelete5.setVisibility(View.VISIBLE);
                imgDelete5.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        mViewModel.ID5_Item.setValue(null);
                        ((TextView) mBinding.llItem.getChildAt(4).findViewById(R.id.itemValue)).setText("");
                        imgDelete5.setVisibility(View.GONE);
                        mViewModel.getBusinessDataByItem(mViewModel.category.getValue().name);
                    }
                });
                break;
            case ItemCategory.ITEM_6:
                mViewModel.ID6_Item.setValue(item);
                ((TextView) mBinding.llItem.getChildAt(5).findViewById(R.id.itemValue)).setText(item.value);
                ImageView imgDelete6 = mBinding.llItem.getChildAt(5).findViewById(R.id.imgdelete);
                imgDelete6.setVisibility(View.VISIBLE);
                imgDelete6.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        mViewModel.ID6_Item.setValue(null);
                        ((TextView) mBinding.llItem.getChildAt(5).findViewById(R.id.itemValue)).setText("");
                        imgDelete6.setVisibility(View.GONE);
                        mViewModel.getBusinessDataByItem(mViewModel.category.getValue().name);
                    }
                });
                break;
        }
        mViewModel.getBusinessDataByItem(mViewModel.category.getValue().name);
    }

    @Override
    protected void onDestroy() {
        unregisterReceiver(usbReceiver);
        super.onDestroy();
    }

    public void onBtnQueryClick(View view) {
        beep();
        mViewModel.getBusinessDataByItem(mViewModel.category.getValue().name);
    }

    public void onBackClick(View view) {
        beep();
        finish();
    }

    public void onDataOutClick(View view) {
        beep();
        exportToExcel();
    }

    private void toExcelFail(String msg) {
        runOnUiThread(() -> {
            if (exportPd != null)
                exportPd.dismiss();
        });
        ToastUtils.showLong(msg);
    }

    private void toExcelSuccess() {
        runOnUiThread(() -> {
            if (exportPd != null)
                exportPd.dismiss();
        });
        ToastUtils.showLong(String.format(Locale.getDefault(), "导出成功：%s", excelName));
    }


    /**
     * 导出到U盘中
     */
    private void exportToExcel() {

        storageDevices = UsbMassStorageDevice.getMassStorageDevices(this);

        if (storageDevices.length <= 0) {
            ToastUtils.showShort("没有发现usb存储设备");
            return;
        }

        if (!checkPermission(storageDevices[0])) {  //检查是否有权限
            mUsbManager.requestPermission(storageDevices[0].getUsbDevice(), pendingIntent);
            return;
        }

        saveToExcel();
    }


    /**
     * 保存excel
     */
    private void saveToExcel() {
        if (reportAdapter.getData() == null || reportAdapter.getData().isEmpty()) {
            ToastUtils.showShort("请先查询需要导出的数据！");
            return;
        }
        exportPd = new ProgressDialog(this);
        exportPd.setTitle("导出数据中，请稍等...");
        exportPd.setCancelable(false);
        exportPd.setCanceledOnTouchOutside(false);
        exportPd.show();

        AppExecutors.getInstance().queryIO()
                .submit(() -> {
                    try {
                        UsbFile root = readDevice(storageDevices[0]).getRootDirectory();
                        if (root == null)
                            return;

                        excelName = new SimpleDateFormat("yyyyMMddHHmm", Locale.getDefault())
                                .format(new Date()) + ".xls";

                        // todo 导出数据格式自定义
                        List<Business> data = reportAdapter.getData();
                        BusinessSheet sheet = new BusinessSheet(data, "sheet", new AdditionalColumn[]{new AdditionalColumn("名称1", "item1")});
                        BusinessTable table = new BusinessTable(excelName, new BusinessSheet[]{sheet});
                        File tempExcelFile = new File(getCacheDir().getAbsoluteFile(), excelName);

                        if (tempExcelFile.exists())
                            tempExcelFile.delete();

                        ExcelUtils.toExcel(getCacheDir().getAbsolutePath(), table);

                        if (tempExcelFile.exists()) { //文件存在时
                            if (UsbHelper.saveSDFileToUsb(tempExcelFile, root, null)) {
                                toExcelSuccess();
                            } else {
                                toExcelFail("导出失败，请重试。");
                            }
                        } else {
                            toExcelFail("导出失败，请重试。");
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                        toExcelFail("导出失败，请重新拔插usb设备。");
                    }
                });
    }

    /**
     * 根据设备获取路径
     *
     * @param device
     * @return
     */
    public FileSystem readDevice(UsbMassStorageDevice device) {
        try {

            if (!checkPermission(device)) {  //检查是否有权限
                mUsbManager.requestPermission(device.getUsbDevice(), pendingIntent);
                return null;
            }

            device.init();//使用设备之前需要进行 初始化
            Partition partition = device.getPartitions().get(0); //仅使用设备的第一个分区
            FileSystem currentFs = partition.getFileSystem();
            // currentFs.getCapacity(); //容量大小
            // currentFs.getOccupiedSpace(); //已使用大小
            // currentFs.getFreeSpace();  //未使用的大小
            UsbFile root = currentFs.getRootDirectory();//获取根目录
            String deviceName = currentFs.getVolumeLabel();//获取设备标签
            return currentFs;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 检查usb设备的权限
     *
     * @param device
     * @return
     */
    public boolean checkPermission(UsbMassStorageDevice device) {
        if (mUsbManager == null) {
            return false;
        }
        if (mUsbManager.hasPermission(device.getUsbDevice())) {//有就直接读取设备是否有权限
            return true;
        } else {
            return false;
        }
    }

    private final BroadcastReceiver usbReceiver = new BroadcastReceiver() {

        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (ACTION_USB_PERMISSION.equals(action)) {
                synchronized (this) {
                    UsbDevice device = intent.getParcelableExtra(UsbManager.EXTRA_DEVICE);
                    if (intent.getBooleanExtra(UsbManager.EXTRA_PERMISSION_GRANTED, false)) {
                        if (device != null) {
                            saveToExcel();
                        }
                    } else {
                        Log.d("res", "permission denied for device " + device);
                    }
                }
            }
        }
    };

    //增加类别选择框
    public void showCategory(List<Category> categories){
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("请选择分类：");

        final String items[] = new String[categories.size()];
        for (int i = 0; i <categories.size() ; i++) {
            items[i] = categories.get(i).name;
        }
        builder.setSingleChoiceItems(items, -1, new DialogInterface.OnClickListener() {

            @Override
            public void onClick(DialogInterface dialog, int which) {
                beep();
                String item = items[which];
                LegoMessageManager.getInstance().sendMessage(Options.MSG_REPORT_CATEGORY_SELECT_ITEM, categories.get(which));
                dialog.dismiss();

            }
        });

        builder.show();
    }

    //显示分类选择
    private void showSingleDialog(List<Item> data){
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("请选择属性：");

        final String items[] = new String[data.size()];
        for (int i = 0; i <data.size() ; i++) {
            items[i] = data.get(i).value;
        }
        builder.setSingleChoiceItems(items, -1, new DialogInterface.OnClickListener() {

            @Override
            public void onClick(DialogInterface dialog, int which) {
                beep();
                String item = items[which];
                LegoMessageManager.getInstance().sendMessage(Options.MSG_REPORT_SELECT_ITEM, data.get(which));
                dialog.dismiss();

            }
        });

        builder.show();
    }



    @OnMessage(value = Options.MSG_REPORT_CATEGORY_SELECT_ITEM)
    public void getCategory(Category category) {
        mViewModel.category.setValue(category);
    }




}
